# -*- coding: utf-8 -*-
from datetime import datetime
from django.db import transaction
from django.http import JsonResponse
from rest_framework import views, status
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from myapp.models import Shop, Type, Catalogue, Orders
from utils.save_image import save_file
from django.forms.models import model_to_dict


class ShopMessage(views.APIView):
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

    @transaction.atomic
    def post(self, request):
        params = request.data
        shop_name = params.get("shopName", None)
        address = params.get("address", None)
        phone = params.get("phone", None)
        avatar = request.FILES.get('image', None)
        avatar = save_file(avatar, "shops")
        business_hours = params.get("businessHours", None)
        is_open = params.get("isOpen", None)
        details = params.get("details", None)
        if not shop_name or not address or not phone or not avatar or not business_hours or not is_open or not details:
            return Response({"error": "please check your params"},
                            status=status.HTTP_400_BAD_REQUEST)
        try:
            shop, _ = Shop.objects.select_for_update().update_or_create(
                user=request.user,
            )
            shop.shop_name = shop_name
            shop.address = address
            shop.phone = phone
            shop.avatar = avatar
            shop.business_hours = business_hours
            shop.is_open = int(is_open)
            shop.details = details
            shop.save()
            if _:
                return JsonResponse({"msg": "添加成功"})
            return JsonResponse({"msg": "更新成功"})
        except shop.DoesNotExist:
            transaction.rollback()
            return JsonResponse({"error": "添加失败"},
                                status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def get(self, request):
        try:
            shop = Shop.objects.filter(user=request.user).first()
            return JsonResponse({"msg": model_to_dict(shop)})
        except shop.DoesNotExist:
            return JsonResponse({"msg": []})


class Catalogues(views.APIView):
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

    @transaction.atomic
    def post(self, request):
        params = request.data
        file = request.FILES.get('avatar', None)
        if not file:
            return Response({'error': '获取图片失败'},
                            status=status.HTTP_400_BAD_REQUEST)
        avatar = save_file(file, 'foods')
        name = params.get('name', None)
        price = params.get('price', None)
        detail = params.get('details', None)
        sort = params.get('type', None)
        if not name or not price or not sort:
            return JsonResponse({'error': '缺少必要参数'},
                                status=status.HTTP_400_BAD_REQUEST)
        try:
            shop = Shop.objects.get(user=request.user)
            _type, created = Type.objects.select_for_update().get_or_create(
                attr=sort,
                shop=shop,
            )
            catalogue = Catalogue.objects.select_for_update().create(
                name=name,
                image=avatar,
                price=price,
                detail=detail,
                tid=_type,
            )
            return JsonResponse({"msg": "添加菜品成功"})
        except catalogue.DoesNotExist:
            transaction.rollback()
            return JsonResponse({"error": "添加菜品失败"},
                                status=status.HTTP_400_BAD_REQUEST)

    def get(self, request):
        params = request.GET
        seller = params.get('uid', None)
        desk = params.get('did', None)
        try:
            shop = Shop.objects.get(user_id=seller)
            _type = Type.objects.filter(shop=shop)
            menu = []
            for item in _type:
                sorts = item.catalogue_set.all()
                _t = []
                for sort in sorts:
                    _t.append({
                        "cid": sort.id,
                        "name": sort.name,
                        "image": sort.image,
                        "price": sort.price,
                        "details": sort.detail,
                        "type": sort.tid.attr,
                    })
                menu.append(_t)
            return JsonResponse({"msg": menu})
        except shop.DoesNotExist:
            return JsonResponse({"error": "获取菜单失败"},
                                status=status.HTTP_400_BAD_REQUEST)


class Order(views.APIView):
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

    @transaction.atomic
    def post(self, request):
        params = request.data
        seller = params.get('uid', None)
        desk = params.get('did', None)
        foods = params.get('foods', None)
        foods = str(foods).split(',')
        if not seller or not desk or not foods:
            return JsonResponse({'error': '缺少必要参数'},
                                status=status.HTTP_400_BAD_REQUEST)
        try:
            shop = Shop.objects.get(user_id=seller)
            for food in foods:
                catalogue = Catalogue.objects.get(id=int(food))
                try:
                    order = Orders.objects.select_for_update().create(
                        oid=datetime.now().strftime('%Y%m%d%H%M%S'),
                        desk=desk,
                        food=catalogue,
                        shop=shop,
                        user=request.user,
                    )
                except order.DoesNotExist:
                    transaction.rollback()
                    return JsonResponse(
                        {'error': '点餐失败'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
            return JsonResponse({"msg": "已下单"})
        except shop.DoesNotExist:
            transaction.rollback()
            return JsonResponse({'error': '点餐失败'},
                                status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def get(self, request):
        params = request.GET
        tag = params.get('tag', None)
        if tag == 'seller':
            order_list = []
            try:
                orders = Shop.objects.get(user=request.user).orders_set.all()
                for order in orders:
                    data = {
                        'name': order.food.name,
                        'image': order.food.image,
                        'price': order.food.price,
                        'details': order.food.detail,
                        'type': order.food.tid.attr,
                        'desk': order.desk,
                        'oid': order.oid,
                        'time': order.create_time,
                    }
                    order_list.append(data)
                return JsonResponse({"msg": order_list})
            except orders.none():
                return JsonResponse({"error": "获取商家订单信息失败"},
                                    status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        else:
            oid = params.get('oid', '')
            if oid == '':
                try:
                    res = []
                    order = Orders.objects.filter(user=request.user).all()
                    for o in order:
                        res.append({"oid": o.oid, "name": o.food.name})
                    return JsonResponse({"msg": res})
                except order.DoesNotExist:
                    return JsonResponse({'error': '获取用户订单失败'})
            try:
                order = Orders.objects.filter(
                    user=request.user, oid=oid).first()
                return JsonResponse({"msg": order})
            except order.DoesNotExist:
                return JsonResponse({"error": "获取个人订单失败"},
                                    status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class IsOpen(views.APIView):
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

    @transaction.atomic
    def get(self, request):
        try:
            shop = Shop.objects.get(user=request.user)
            params = request.GET
            is_open = params.get('isOpen', None)
            if (is_open is not None) and (int(is_open) == 1):
                shop.is_open = 0
            else:
                shop.is_open = 1
            shop.save()
            return JsonResponse({'msg': '状态修改成功'})
        except shop.DoesNotExist:
            transaction.rollback()
            return JsonResponse({'error': '服务器错误，请稍后再试'},
                                status=status.HTTP_500_INTERNAL_SERVER_ERROR)
